<template>

	<swiper class="home-swiper" :current="tabindex" @change="change">
		<swiper-item v-for="(item,index) in list" :key="index" class="swiper-item">
			<list-item :list_detail="list_catchDate[index]" :load="load[index]" @loadmore="loadmore"></list-item>
		</swiper-item>

	</swiper>
</template>

<script>
	import listItem from './list-item.vue'
	export default {
		components: {
			listItem
		},
		props: {
			list: {
				type: Array,
				default () {
					return []
				}
			},
			tabindex: {
				type: Number,
				default: 0
			}
		},

		data() {
			return {
				list_detail: [],
				//js限制无法改变引用，需要在下面使用￥set对它赋值
				list_catchDate: {},
				load:{},
				pagesize:10
			};
		},
		watch: {
			//监听第一次加载list数据变化后触发
			list(newValue, oldValue) { 
				if (newValue.length === 0) return
				this.list_catchDate={}
				this.load={}				
				this.get_list(this.tabindex)
			}
		},
		created() { 
		},
		methods: {
			loadmore(){
				//判断是否最下面数据，是就不在执行下拉
				if(this.load[this.tabindex].loading==='noMore') return
				//每个load下标项++
				this.load[this.tabindex].page++
				this.get_list(this.tabindex) 
				//console.log(this.tabindex,"拉了几次:",this.load[this.tabindex].page)
			},
			change(e) {
				//将滑动的索引传递到父组件
				const {
					current
				} = e.detail
				this.$emit("change", current)
				//TODO 当数据不存在 或 长度为0的情况，才请求数据
				if (!this.list_catchDate[current] || this.list_catchDate[current].length === 0) {
					this.get_list(current)
				}

			},
			get_list(current) {
				 var that=this
				//对load初始化，如果为空就赋值:初始页码和加载状态
				if(!this.load[current])
				{
					this.load[current]={
						page:1,
						loading:"loading"
					}
				}
				
				//调用get_list云函数获取文章详情信息
				this.$api.get_list({
					name: this.list[current].name,
					page: this.load[current].page,
					pagesize:this.pagesize
				}).then((res) => { 
					const {
						data
					} = res	 
				    //判断是否最后面一页，改变每个 load[索引] 中loading的加载方式
						if(data.length===0)
						{
							let oldload={}
							oldload.loading="noMore"
							oldload.page=this.load[current].page
							this.$set(this.load,current,oldload)
							//强制渲染页面
							this.$forceUpdate()
							return
						}
					//this.list_detail=data  
					//js限制无法改变引用，需要在下面使用￥set对它赋值
					//this.list_catchDate[current]=data
					 
					//合并新旧数据 ...data是数组扩展符
					let oldList=this.list_catchDate[current] || []
					oldList.push(...data)   					
					
					this.$set(this.list_catchDate, current, oldList) //懒加载					
				})
			}
		},
	}
</script>

<style lang="scss">
	.home-swiper {
		height: 100%;

		.swiper-item {
			height: 100%;

		}
	}
</style>
